package com.proton.carepatchtemp.login.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.base.BaseActivity;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.database.dao.RegisterInfo;
import com.proton.carepatchtemp.database.dao.SignActvts;
import com.proton.carepatchtemp.utils.FormUtils;
import com.proton.carepatchtemp.utils.NumUtils;
import com.proton.carepatchtemp.utils.TastyUtils;
import com.proton.carepatchtemp.utils.VaildUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.SignCenter;
import com.sdsmdg.tastytoast.TastyToast;


public class RegisterActivity extends BaseActivity implements View.OnClickListener {

    RegisterInfo info = new RegisterInfo();
    private ImageButton mBtn_back_login;
    private EditText mEt_phone_number;
    private EditText mEt_pwd;
    private EditText mEt_repeat_pwd;
    private EditText mEt_verification_code;
    private TextView mTv_send_verification;
    private FrameLayout mCount_down_timer;
    private ImageView mIv_timer;
    private TextView mTv_timer;
    private Button mTv_complete;
    private TextView mTv_go_login;
    private TextView mTv_pravacy;
    private TextView mTv_agreeement;
    private boolean complete = false;

    @Override
    public void dealEvent(MainEvent event) {
        try {
            if (null == event || isFinishing()) {
                return;
            }
            int id = event.getId();
            switch (id) {
                case Codes.NET_SIGN_REGISTER_GET_CAP:
                    if (event.isSuccess() || event.isInterval()) {
                        if (event.isInterval()) {
                            //                        Toast.makeText(this,R.string.get_too_much_captime, Toast.LENGTH_SHORT).show();
                            TastyUtils.makeTextShort(R.string.get_too_much_captime, TastyToast.CONFUSING);
                        }
                        int capTime = NumUtils.getIntNum(event.getMsg());
                        capTime = capTime == 0 ? -1 : capTime;
                        info.setCapTime(capTime);
                        sendMsg();
                    } else {
                        Toast.makeText(this, event.getMsg(), Toast.LENGTH_LONG).show();
                    }
                    break;
                case Codes.NET_SIGN_REGISTER_VALI_CAP:
                    if (event.isSuccess()) {
                        String msg = event.getMsg();
                        info.setCode(msg);
                        dealValiCapSuccess();
                    } else {
                        Toast.makeText(this, event.getMsg(), Toast.LENGTH_LONG).show();
                    }
                    break;
                case Codes.NET_SIGN_REGISTER:
                    if (event.isSuccess()) {
                        complete = true;
                        dealRegisterSuccess();
                    } else {
                        Toast.makeText(this, event.getMsg(), Toast.LENGTH_LONG).show();
                    }
                    break;
                case Codes.NET_SIGN_LOGIN_REGISTER:
                    if (event.isSuccess()) {
                        dealLoginSuccess();
                    } else {

                    }
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        bindViews();
        setListener();
    }


    @Override
    public void setListener() {
        mBtn_back_login.setOnClickListener(this);
        mTv_complete.setOnClickListener(this);
        mTv_send_verification.setOnClickListener(this);

        mTv_pravacy.setOnClickListener(v -> {
            Intent goPrivacy = new Intent(RegisterActivity.this, PrivacyPoliciesActivity.class);
            goPrivacy.putExtra("type", 1);
            startActivity(goPrivacy);
        });

        mTv_agreeement.setOnClickListener(v -> {
            Intent goPrivacy = new Intent(RegisterActivity.this, PrivacyPoliciesActivity.class);
            goPrivacy.putExtra("type", 2);
            startActivity(goPrivacy);
        });

        mTv_go_login.setOnClickListener(v -> {
            Intent goLogin = new Intent(RegisterActivity.this, LoginAuthActivity.class);
            startActivity(goLogin);
            finish();
        });

    }

    private void bindViews() {
        mBtn_back_login = findViewById(R.id.btn_back_login);
        mEt_phone_number = findViewById(R.id.et_phone_number);
        mEt_pwd = findViewById(R.id.et_pwd);
        mEt_repeat_pwd = findViewById(R.id.et_repeat_pwd);
        mEt_verification_code = findViewById(R.id.et_verification_code);
        mTv_send_verification = findViewById(R.id.tv_send_verification);
        mCount_down_timer = findViewById(R.id.count_down_timer);
        mIv_timer = findViewById(R.id.iv_timer);
        mTv_timer = findViewById(R.id.tv_timer);
        mTv_complete = findViewById(R.id.tv_complete);
        mTv_go_login = findViewById(R.id.tv_go_login);
        mTv_pravacy = findViewById(R.id.tc_privacy_policies);
        mTv_agreeement = findViewById(R.id.tv_service_agreement);

        mTv_pravacy.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        mTv_agreeement.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            //  返回登录
            case R.id.btn_back_login:
                finish();
                break;

            //  完成注册按钮
            case R.id.tv_complete:
//                if(!Settings.isTest){
//                    Intent toGuideIntent = new Intent(RegisterActivity.this,GuideActivity.class);
//                    startActivity(toGuideIntent);
//                    finish();
//                }
                dealGetRightCaptcha();
                if (!isComplete()) {
                    //Toast.makeText(this,R.string.un_current_captcha, Toast.LENGTH_LONG).show();
                    return;
                }
                complete = false;
                break;

            case R.id.tv_send_verification:
                if (isInPutReglar()) {
                    SignCenter.getRegisterCap(info.getMobile());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onEventMainThread(MainEvent event) {
        dealOnEvent(event);
    }


    /**
     * 发送获取验证码请求
     */
    private void sendMsg() {
        try {
            Toast.makeText(this, getString(R.string.post_verification_success), Toast.LENGTH_SHORT).show();
            mTv_send_verification.setVisibility(View.INVISIBLE);
            mCount_down_timer.setVisibility(View.VISIBLE);
            final RotateAnimation rotateAnimation = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            rotateAnimation.setDuration(1000);
            mIv_timer.setAnimation(rotateAnimation);
            new CountDownTimer(60000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    mTv_timer.setTextColor(Color.parseColor("#7F7F7F"));
                    mTv_timer.setText((int) (millisUntilFinished / 1000) + "S");
                    mIv_timer.startAnimation(rotateAnimation);
                }

                @Override
                public void onFinish() {
                    //  倒计时完成后恢复
                    mIv_timer.clearAnimation();
                    mTv_send_verification.setVisibility(View.VISIBLE);
                    mCount_down_timer.setVisibility(View.INVISIBLE);
                }
            }.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isInPutReglar() {
        String phone = FormUtils.getString(mEt_phone_number);
        String pwd = FormUtils.getString(mEt_pwd);
        String rePwd = FormUtils.getString(mEt_repeat_pwd);
        if (TextUtils.isEmpty(phone)) {
            TastyUtils.makeTextShort(R.string.no_value_phone_number, TastyToast.CONFUSING);
            return false;
        }
        if (TextUtils.isEmpty(pwd)) {
            TastyUtils.makeTextShort(R.string.no_value_pwd, TastyToast.CONFUSING);
            return false;
        }
        if (TextUtils.isEmpty(rePwd)) {
            TastyUtils.makeTextShort(R.string.no_value_repwd, TastyToast.CONFUSING);
            return false;
        }
        if (VaildUtils.valiMobile(phone)) {
            info.setMobile(phone);
        } else {
            TastyUtils.makeTextShort(R.string.invalid_phone_number, TastyToast.CONFUSING);
            return false;
        }
        if (VaildUtils.isRepeat(pwd, rePwd)) {
            info.setPwd(pwd);
        } else {
            TastyUtils.makeTextShort(R.string.no_same_pwd, TastyToast.CONFUSING);
            return false;
        }
        if (pwd.length() < 6) {
            TastyUtils.makeTextShort("密码不得少于6位！", TastyToast.CONFUSING);
            return false;
        }
        return true;
    }


    private void dealGetRightCaptcha() {
        String captcha = FormUtils.getString(mEt_verification_code);
        if (TextUtils.isEmpty(captcha)) {
            Toast.makeText(this, R.string.no_value_captcha, Toast.LENGTH_SHORT).show();
        }
        SignCenter.valiRegCap(info.getMobile(), captcha);
    }

    private void dealValiCapSuccess() {
        SignCenter.register(info);
    }


    public void dealRegisterSuccess() {
        boolean result = SignCenter.login(info, SignActvts.REG);
        LogUtils.e(result);
        if (result) {
            LogUtils.e("Login Success");
        }
    }

    private void dealLoginSuccess() {
        Intent toGuideIntent = new Intent(RegisterActivity.this, GuideActivity.class);
        startActivity(toGuideIntent);
        finish();
    }

    public boolean isComplete() {
        return complete;
    }

}
